package com.information.controller;

import com.information.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/cache")
public class CacheController {
    
    private final RedisService redisService;
    
    @Autowired
    public CacheController(RedisService redisService) {
        this.redisService = redisService;
    }

    /**
     * 获取缓存状态
     */
    @GetMapping("/status")
    public ResponseEntity<Map<String, Object>> getCacheStatus() {
        Map<String, Object> status = new HashMap<>();
        status.put("ping", redisService.ping());
        status.put("connectionInfo", redisService.getConnectionInfo());
        status.put("testConnection", redisService.testConnection());
        return ResponseEntity.ok(status);
    }

    /**
     * 按ID删除用户缓存
     * @param id
     */
    @DeleteMapping("/users/{id}")
    public ResponseEntity<Map<String, String>> evictUserCache(@PathVariable Long id) {
        redisService.evictUser(id);
        Map<String, String> response = new HashMap<>();
        response.put("message", "用户缓存已清除: " + id);
        return ResponseEntity.ok(response);
    }

    /**
     * 按用户名删除用户缓存
     * @param username
     */
    @DeleteMapping("/users/username/{username}")
    public ResponseEntity<Map<String, String>> evictUserCacheByUsername(@PathVariable String username) {
        redisService.evictUserByUsername(username);
        Map<String, String> response = new HashMap<>();
        response.put("message", "用户缓存已清除: " + username);
        return ResponseEntity.ok(response);
    }

    /**
     * 删除所有用户缓存
     */
    @DeleteMapping("/users/all")
    public ResponseEntity<Map<String, String>> evictAllUsersCache() {
        redisService.evictAllUsers();
        Map<String, String> response = new HashMap<>();
        response.put("message", "所有用户列表缓存已清除");
        return ResponseEntity.ok(response);
    }

    @GetMapping("/sync-status")
    public ResponseEntity<Map<String, Object>> getCacheSyncStatus() {
        Map<String, Object> status = new HashMap<>();
        status.put("binlogListenerActive", true); // 可以添加实际状态检查
        status.put("lastSyncTime", System.currentTimeMillis());
        status.put("message", "缓存同步监听正常运行");
        return ResponseEntity.ok(status);
    }
}